import React, { createContext, useContext, useState, useEffect, useMemo, ReactNode } from 'react';
import { Theme, ThemeMode, ThemeContextType, getTheme, applyTheme } from '../../styles/theme';
import { Sun, Moon } from 'lucide-react';

// 主题切换Hook
export const useTheme = (): ThemeContextType => {
  const [themeMode, setThemeMode] = useState<ThemeMode>(() => {
    // 从localStorage读取保存的主题偏好
    const saved = localStorage.getItem('theme-mode');
    return (saved as ThemeMode) || 'auto';
  });
  
  const theme = useMemo(() => getTheme(themeMode), [themeMode]);
  
  // 监听系统主题变化
  useEffect(() => {
    if (themeMode === 'auto') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      const handleChange = () => {
        const newTheme = getTheme('auto');
        applyTheme(newTheme);
      };
      
      mediaQuery.addEventListener('change', handleChange);
      return () => mediaQuery.removeEventListener('change', handleChange);
    }
  }, [themeMode]);
  
  // 应用主题
  useEffect(() => {
    applyTheme(theme);
  }, [theme]);
  
  // 保存主题偏好
  useEffect(() => {
    localStorage.setItem('theme-mode', themeMode);
  }, [themeMode]);
  
  const toggleTheme = () => {
    setThemeMode(prev => {
      switch (prev) {
        case 'light':
          return 'dark';
        case 'dark':
          return 'auto';
        case 'auto':
          return 'light';
        default:
          return 'light';
      }
    });
  };
  
  const setTheme = (mode: ThemeMode) => {
    setThemeMode(mode);
  };
  
  return {
    theme,
    themeMode,
    setTheme,
    toggleTheme,
    isDark: theme.mode === 'dark' || (theme.mode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches),
    isLight: theme.mode === 'light' || (theme.mode === 'auto' && !window.matchMedia('(prefers-color-scheme: dark)').matches),
  };
};

// 主题上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider = ({ children }: { children: ReactNode }) => {
  const themeState = useTheme();
  
  return (
    <ThemeContext.Provider value={themeState}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useThemeContext = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useThemeContext must be used within a ThemeProvider');
  }
  return context;
};

// 主题切换组件
export interface ThemeToggleProps {
  className?: string;
  size?: 'sm' | 'md' | 'lg';
  variant?: 'default' | 'outline' | 'ghost';
}

export const ThemeToggle: React.FC<ThemeToggleProps> = ({ 
  className = '', 
  size = 'md',
  variant = 'default'
}) => {
  const { themeMode, toggleTheme, isDark } = useThemeContext();
  
  const sizeClasses = {
    sm: 'p-1.5 w-8 h-8',
    md: 'p-2 w-10 h-10',
    lg: 'p-2.5 w-12 h-12'
  };
  
  const iconSizes = {
    sm: 16,
    md: 20,
    lg: 24
  };
  
  const variantClasses = {
    default: 'bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700',
    outline: 'border border-gray-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-800',
    ghost: 'hover:bg-gray-100 dark:hover:bg-gray-800'
  };
  
  return (
    <button
      onClick={toggleTheme}
      className={`
        ${sizeClasses[size]}
        ${variantClasses[variant]}
        rounded-lg transition-all duration-200 
        text-gray-700 dark:text-gray-300
        focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2
        ${className}
      `}
      aria-label={`切换主题 (当前: ${themeMode})`}
      title={`当前主题: ${themeMode}`}
    >
      {isDark ? (
        <Sun size={iconSizes[size]} className="transition-transform duration-200 rotate-0 scale-100" />
      ) : (
        <Moon size={iconSizes[size]} className="transition-transform duration-200 rotate-0 scale-100" />
      )}
    </button>
  );
};

// 主题状态指示器
export const ThemeIndicator: React.FC<{ className?: string }> = ({ className = '' }) => {
  const { themeMode, isDark } = useThemeContext();
  
  const getThemeLabel = () => {
    switch (themeMode) {
      case 'light':
        return '浅色';
      case 'dark':
        return '深色';
      case 'auto':
        return `自动 (${isDark ? '深色' : '浅色'})`;
      default:
        return '未知';
    }
  };
  
  return (
    <span className={`text-sm text-gray-600 dark:text-gray-400 ${className}`}>
      主题: {getThemeLabel()}
    </span>
  );
};

// 主题选择器
export interface ThemeSelectorProps {
  className?: string;
  showLabel?: boolean;
}

export const ThemeSelector: React.FC<ThemeSelectorProps> = ({ 
  className = '',
  showLabel = true
}) => {
  const { themeMode, setTheme } = useThemeContext();
  
  const themes: { value: ThemeMode; label: string; icon: React.ReactNode }[] = [
    { value: 'light', label: '浅色', icon: <Sun size={16} /> },
    { value: 'dark', label: '深色', icon: <Moon size={16} /> },
    { value: 'auto', label: '自动', icon: <div className="w-4 h-4 rounded-full bg-gradient-to-r from-yellow-400 to-blue-600" /> }
  ];
  
  return (
    <div className={`flex items-center gap-2 ${className}`}>
      {showLabel && (
        <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
          主题:
        </span>
      )}
      <div className="flex rounded-lg border border-gray-300 dark:border-gray-600 overflow-hidden">
        {themes.map((theme) => (
          <button
            key={theme.value}
            onClick={() => setTheme(theme.value)}
            className={`
              px-3 py-2 text-sm font-medium transition-colors duration-200
              flex items-center gap-2
              ${
                themeMode === theme.value
                  ? 'bg-primary-500 text-white'
                  : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              }
            `}
            aria-label={`切换到${theme.label}主题`}
          >
            {theme.icon}
            <span>{theme.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
};